<template>
  <div class="staff-status-container">
    <h2>会议室状态管理</h2>
    <table>
      <thead>
        <tr>
          <th>会议室名称</th>
          <th>当前状态</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="room in mockRooms" :key="room.id">
          <td>{{ room.room_name }}</td>
          <td>{{ room.status }}</td>
          <td>
            <button @click="changeStatus(room, '使用')" :disabled="room.status === '使用'">设为使用中</button>
            <button @click="changeStatus(room, '空闲')" :disabled="room.status === '空闲'">设为空闲</button>
            <button @click="changeStatus(room, '维护')" :disabled="room.status === '维护'">设为维护中</button>
          </td>
        </tr>
      </tbody>
    </table>

    <div class="audit-section">
      <h3>取消申请审核</h3>
      <div v-if="unauditedRequests.length === 0" class="no-requests">暂无待审核的取消申请</div>
      <table v-else class="audit-table">
        <thead>
          <tr>
            <th>订单ID</th>
            <th>用户</th>
            <th>申请时间</th>
            <th>退款比例</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="request in unauditedRequests" :key="request.id">
            <td>{{ request.orderId }}</td>
            <td>{{ request.realName || '未知用户' }}</td>
            <td>{{ formatTime(request.cancelTime) }}</td>
            <td>{{ request.refundRate * 100 }}%</td>
            <td>
              <button @click="approveRequest(request, '已通过')">通过</button>
              <!-- <button @click="approveRequest(request, '已拒绝')">拒绝</button> -->
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import axios from '../axios';
import { useAutoRefresh } from '../utils/useAutoRefresh';
import { useUserStore } from '../store/UserStore';
import { useWebSocketStore } from '../store/WebSocketStore';

const userStore = useUserStore();

const mockRooms = ref([]);
const unauditedRequests = ref([]); // 存储待审核的取消申请

const fetchRooms = async () => {
  try {
    const response = await axios.get('/rooms/list');
    mockRooms.value = response.data.data;
  } catch (error) {
    alert('获取会议室状态失败');
  }
};

// 获取所有待审核的取消申请
const fetchUnauditedRequests = async () => {
  try {
    const response = await axios.get('/cancel/unaudited');
    // alert(JSON.stringify(response.data.data));
    unauditedRequests.value = response.data.data;
  } catch (error) {
    alert('获取待审核取消申请失败');
  }
};

// 审核取消申请
const approveRequest = async (request, status) => {
  if (!confirm(`确定通过此申请吗？`)) return;

  try {
    await axios.put(`/cancel/${request.orderId}/approve`, {
      auditStatus: status,
    });

    alert(`取消申请已${status}`);

    // 刷新列表
    fetchUnauditedRequests();
  } catch (error) {
    alert(error.response?.data?.message || '审核失败，请重试');
  }
};

// 时间格式化（复用 formatTime）
const formatTime = (time) => {
  if (!time) return '';
  const date = new Date(time);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}`;
};

onMounted(async () => {
  await fetchRooms();
  await fetchUnauditedRequests();

  useAutoRefresh(async () => {
    await fetchRooms();
  }, 2000);
});

// 处理会议室状态更新
const handleRoomStatusUpdated = (payload) => {
  const index = mockRooms.value.findIndex(r => r.id === payload.roomId);
  if (index > -1) {
    mockRooms.value[index].status = payload.status;
  }
};

// 处理取消申请提交事件
const handleCancelRequestSubmitted = (payload) => {
  unauditedRequests.value.push(payload.request);
};

onMounted(() => {
  const wsStore = useWebSocketStore();
  wsStore.on('server:room-status-updated', handleRoomStatusUpdated);
  wsStore.on('server:cancel-request-submitted', handleCancelRequestSubmitted);
});

onUnmounted(() => {
  const wsStore = useWebSocketStore();
  wsStore.off('server:room-status-updated', handleRoomStatusUpdated);
  wsStore.off('server:cancel-request-submitted', handleCancelRequestSubmitted);
});

const changeStatus = async (room, newStatus) => {
  try {
    await axios.put(`/rooms/${room.id}/status`, { status: newStatus });
    alert(`状态更新为：${newStatus}`);
    await fetchRooms();
  } catch (error) {
    alert(error.response?.data?.error || '状态更新失败');
  }
};
</script>

<style scoped>
table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
}
th, td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #e5e7eb;
}
button {
  margin-right: 5px;
  padding: 5px 10px;
  background-color: #3b82f6;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
button:disabled {
  background-color: #d1d5db;
  cursor: not-allowed;
}

.audit-section {
  margin-top: 40px;
}

.audit-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 10px;
}

.audit-table th,
.audit-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #e5e7eb;
}

.audit-table button {
  margin-right: 8px;
  padding: 6px 12px;
  background-color: #10b981;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.audit-table button:hover {
  background-color: #059669;
}

.audit-table button:nth-child(2) {
  background-color: #f87171;
}

.audit-table button:nth-child(2):hover {
  background-color: #ef4444;
}

.no-requests {
  color: #6b7280;
  font-style: italic;
}
</style>